import { defineComponent } from 'vue'
import type { PropType } from 'vue'
import type { JsonChangeValue, JsonSchema } from './types'
import { components } from './components'

const RowsView = defineComponent({
  name: 'RowsView',
  props: {
    schemas: {
      type: Array as PropType<JsonSchema[]>,
      default: () => []
    }
  },
  emits: ['valueChange'],
  setup(
    props,
    ctx: {
      emit: (event: 'valueChange', payload: JsonChangeValue) => void
    }
  ) {
    const handleValueChange = (v: JsonChangeValue) => {
      ctx.emit('valueChange', v)
    }
    return () => {
      return (
        <>
          {props.schemas.map((schema: JsonSchema) => {
            if (schema?.children?.length) {
              return components({
                valueChange: handleValueChange,
                schema,
                slots: {
                  default: () => <RowsView onValueChange={(v) => handleValueChange(v)} schemas={schema.children} />
                }
              })
            }
            if (!schema.children?.length && schema?.child) {
              return components({
                valueChange: handleValueChange,
                schema,
                slots: {
                  default: () => (
                    <RowsView onValueChange={(v) => handleValueChange(v)} schemas={[schema.child as JsonSchema]} />
                  )
                }
              })
            }
            return components({
              schema,
              valueChange: handleValueChange,
              slots: schema.slots
            })
          })}
        </>
      )
    }
  }
})

export default RowsView
